#!/bin/bash

# MQTT项目云服务器部署脚本
# 服务器IP: 8.149.243.80

echo "=== MQTT项目部署脚本 ==="
echo "目标服务器: 8.149.243.80"
echo ""

# 检查Node.js是否已安装
if ! command -v node &> /dev/null; then
    echo "错误: 未检测到Node.js，请先安装Node.js"
    exit 1
fi

# 检查npm是否已安装
if ! command -v npm &> /dev/null; then
    echo "错误: 未检测到npm，请先安装npm"
    exit 1
fi

echo "✓ Node.js版本: $(node -v)"
echo "✓ npm版本: $(npm -v)"
echo ""

# 1. 安装依赖
echo "步骤 1/6: 安装后端依赖..."
npm install --production
if [ $? -ne 0 ]; then
    echo "错误: 后端依赖安装失败"
    exit 1
fi
echo "✓ 后端依赖安装完成"
echo ""

# 2. 安装前端依赖
echo "步骤 2/6: 安装前端依赖..."
cd client-vue
npm install
if [ $? -ne 0 ]; then
    echo "错误: 前端依赖安装失败"
    exit 1
fi
echo "✓ 前端依赖安装完成"
echo ""

# 3. 构建前端
echo "步骤 3/6: 构建前端项目..."
npm run build
if [ $? -ne 0 ]; then
    echo "错误: 前端构建失败"
    exit 1
fi
echo "✓ 前端构建完成"
cd ..
echo ""

# 4. 创建日志目录
echo "步骤 4/6: 创建日志目录..."
mkdir -p logs
echo "✓ 日志目录创建完成"
echo ""

# 5. 安装PM2（如果未安装）
echo "步骤 5/6: 检查并安装PM2..."
if ! command -v pm2 &> /dev/null; then
    echo "正在安装PM2..."
    npm install -g pm2
    if [ $? -ne 0 ]; then
        echo "错误: PM2安装失败"
        exit 1
    fi
fi
echo "✓ PM2已就绪"
echo ""

# 6. 使用PM2启动服务
echo "步骤 6/6: 启动服务..."
pm2 stop mqtt-server 2>/dev/null || true
pm2 delete mqtt-server 2>/dev/null || true
pm2 start ecosystem.config.js --env production
if [ $? -ne 0 ]; then
    echo "错误: 服务启动失败"
    exit 1
fi
pm2 save
echo "✓ 服务启动完成"
echo ""

# 显示服务状态
echo "=== 服务状态 ==="
pm2 list
echo ""

echo "=== 部署完成！ ==="
echo "访问地址："
echo "  - 本地: http://localhost:3002"
echo "  - 公网: http://8.149.243.80:3002"
echo ""
echo "常用命令："
echo "  查看日志: pm2 logs mqtt-server"
echo "  重启服务: pm2 restart mqtt-server"
echo "  停止服务: pm2 stop mqtt-server"
echo "  查看状态: pm2 status"
echo ""
